#include <syslog.h>
#include <time.h>
#include "ApplyWeightJsonQuery.h"
#include "qjson/parser.h"
#include "qjson/serializer.h"
#include <QVariant>
#include <QVariantMap>
#include "DbSession.h"

ApplyWeightJsonQuery::ApplyWeightJsonQuery()
{
}

void ApplyWeightJsonQuery::init(const std::stringstream& query)
{
    QJson::Parser parser;
    bool ok;
    QVariantMap result = parser.parse(
            QByteArray(query.str().c_str()), &ok).toMap();
    if (!ok)
    {
        // print error in log
    }
    else
    {
        m_token = result["auth_token"].toString();
        m_weight = result["weight"].toDouble();
    }

    m_status = "Error";
}

void ApplyWeightJsonQuery::process()
{
    int userId = DbSession::getInstance().getUserIdByToken(m_token);

    if (!userId)
    {
        m_status = "Error";
    }
    else
    {
        DbSession::getInstance().addWeight(userId, m_weight);
        m_status = "Ok";
    }
}

std::string ApplyWeightJsonQuery::outToString() const
{
        return "{\"status\":\"" + m_status.toStdString() + "\"}";
}
